package BandB.Tool.GPhoneManager.FileExplorer.Installer;

import java.io.File;
import java.util.LinkedList;
import java.util.List;

import BandB.Tool.GPhoneManager.R;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class Installer extends ListActivity implements OnItemClickListener {

	protected static final String TAG = Installer.class.getSimpleName();
	private ListView backupListView;
	private InstallerAdapter apksListAdapter;
	private List<ApplicationInfo> apksList;
	private TextView noBackupTextView;
	private TextView loadingView;
	// private Button btnMore;
	// private static SettingManager settingManager;
	private ProgressDialog deleteDlg;
	private static final int DELETE_DIALOG = 1;
	private PackageManager mPackageManager;
	private static final String PATH_ROOT = Environment
			.getExternalStorageDirectory().getAbsolutePath();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.backup_list);
		initializeElements();

		mPackageManager = getPackageManager();
		mHandler.sendEmptyMessage(MSG_SHOW_LOADING);
		startLoadingAllApks();
	}

	private void initializeElements() {
		loadingView = (TextView) findViewById(R.id.txtViewBackupLoading);
		noBackupTextView = (TextView) findViewById(R.id.no_backup);
		backupListView = getListView();
		backupListView.setOnItemClickListener(this);
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		if (DELETE_DIALOG == id) {
			deleteDlg = new ProgressDialog(this);
			deleteDlg.setTitle("Delete");
			deleteDlg.setMessage("Delete is processing...");
			deleteDlg.setCancelable(true);
			deleteDlg.setIndeterminate(true);
			return deleteDlg;
		}
		return super.onCreateDialog(id);
	}

	private static final byte MODE_LOADING = 0;
	private static final byte MODE_SHOW_LIST = 1;
	private static final byte MODE_SHOW_NO_ITEM = 2;

	private void setMode(byte mode) {
		switch (mode) {
		case MODE_LOADING:
			loadingView.setVisibility(View.VISIBLE);
			backupListView.setVisibility(View.GONE);
			noBackupTextView.setVisibility(View.GONE);
			break;
		case MODE_SHOW_LIST:
			loadingView.setVisibility(View.GONE);
			backupListView.setVisibility(View.VISIBLE);
			noBackupTextView.setVisibility(View.GONE);
			break;
		case MODE_SHOW_NO_ITEM:
			loadingView.setVisibility(View.GONE);
			backupListView.setVisibility(View.GONE);
			noBackupTextView.setVisibility(View.VISIBLE);
			break;

		default:
			break;
		}
	}

	private void startLoadingAllApks() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				List<File> list = getAllApksInSdcard(PATH_ROOT);

				if (list.size() != 0) {
					apksList = getInfoOfApkList(list);
					apksListAdapter = new InstallerAdapter(Installer.this,
							apksList);
					mHandler.sendEmptyMessage(MSG_SHOW_LIST);
				} else {
					mHandler.sendEmptyMessage(MSG_SHOW_NO_ITEMS);
				}
			}
		}).start();
	}

	private List<ApplicationInfo> getInfoOfApkList(List<File> filesList) {
		Log.i(TAG, "get size " + filesList.size());
		List<ApplicationInfo> list = new LinkedList<ApplicationInfo>();
		for (File file : filesList) {

			PackageInfo packageInfo = mPackageManager.getPackageArchiveInfo(
					file.getAbsolutePath(), PackageManager.GET_ACTIVITIES);
			ApplicationInfo applicationInfo = new ApplicationInfo();
			applicationInfo.setFile(file);
			applicationInfo.setInfo(packageInfo.applicationInfo);
			applicationInfo.setLastModified(file.lastModified());
			applicationInfo.setSize(file.length());

			list.add(applicationInfo);
		}
		return list;
	}

	private void deleteSpecifiedFile(List<ApplicationInfo> list) {
		int size = list.size();
		for (int i = 0; i < size; i++) {
			File oneFile = list.get(i).getFile();
			if (oneFile.exists()) {
				oneFile.delete();
				Log.i(TAG, oneFile.getName() + "delete success!");
			}
		}
	}

	private boolean isApkFile(File file) {
		boolean isApkFile = false;
		String fileName = file.getName();
		Log.e("BackManager", "file name: " + fileName);
		try {
			String fileSuffix = fileName.substring(fileName.lastIndexOf("."),
					fileName.length());
			Log.i(TAG, "current file suffix=" + fileSuffix);
			if (fileSuffix.toLowerCase().equalsIgnoreCase(".apk")) {
				isApkFile = true;
			}
		} catch (Exception e) {
			return false;
		}

		return isApkFile;
	}

	private List<File> getAllApksInSdcard(String filePath) {
		LinkedList<File> fileList = new LinkedList<File>();
		File apkFolder = new File(filePath);
		if (!apkFolder.exists()) {
			apkFolder.mkdirs();
		}
		File[] files = apkFolder.listFiles();
		if (files == null) {
			return fileList;
		}
		int length = files.length;
		for (int i = 0; i < length; i++) {
			String path = files[i].getAbsolutePath();
			Log.i(TAG + "path is :", path);

			if (files[i].isFile() && isApkFile(files[i])) {
				fileList.add(files[i]);
			} else {
				if (files[i].isDirectory()) {
					List<File> temp = getAllApksInSdcard(path);
					for (File file : temp) {
						if (file.isFile() && isApkFile(file)) {
							fileList.add(file);
						}
					}
				}
			}
		}
		return fileList;

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.backup_menu, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (null == apksListAdapter || apksList.size() == 0) {
			Toast
					.makeText(Installer.this, "No backup item",
							Toast.LENGTH_SHORT).show();
			return super.onOptionsItemSelected(item);
		}
		switch (item.getItemId()) {
		case R.id.menu_select_all:
			apksListAdapter.selectAll();
			break;
		case R.id.menu_select_none:
			apksListAdapter.selectNone();
			break;
		case R.id.menu_recover:
			List<ApplicationInfo> checkList = apksListAdapter.getCheckedItem();
			if (checkList.size() == 0) {
				Toast.makeText(this, "You must select at least one file!",
						Toast.LENGTH_LONG).show();
			} else {
				installApp(checkList);
			}
			break;
		case R.id.menu_delete:
			final List<ApplicationInfo> deleteCheList = apksListAdapter
					.getCheckedItem();
			if (deleteCheList.size() == 0) {
				Toast.makeText(this, "You must select one file at least!",
						Toast.LENGTH_LONG).show();
			} else {

				showDialog(DELETE_DIALOG);
				new Thread(new Runnable() {

					@Override
					public void run() {
						deleteSpecifiedFile(deleteCheList);
						final List<File> filesList = getAllApksInSdcard(PATH_ROOT);
						apksList = getInfoOfApkList(filesList);
						runOnUiThread(new Runnable() {

							@Override
							public void run() {
								// TODO Auto-generated method stub
								Log.e("AppBackupManager", "delete sucess!");
								Toast.makeText(Installer.this,
										"delete success!", Toast.LENGTH_LONG)
										.show();
								Installer.this.dismissDialog(DELETE_DIALOG);
								if (apksList.size() == 0) {
									setMode(MODE_SHOW_NO_ITEM);
								} else {
									noBackupTextView.setVisibility(View.GONE);
									apksListAdapter = new InstallerAdapter(
											Installer.this, apksList);
									backupListView.setAdapter(apksListAdapter);
								}
							}
						});
					}
				}).start();
			}
			break;
		}

		return super.onOptionsItemSelected(item);
	}

	public void installApp(List<ApplicationInfo> backupList) {
		for (int i = 0; i < backupList.size(); i++) {
			Log.i(TAG, i + ".install " + backupList.get(i).getFile().getName());

			Uri installUri = Uri.fromFile(backupList.get(i).getFile());
			Intent installIntent = new Intent(Intent.ACTION_VIEW);
			installIntent.setDataAndType(installUri,
					"application/vnd.android.package-archive");
			startActivity(installIntent);
		}

	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		apksListAdapter.setCheckedAt(position);
	}

	private static final int MSG_SHOW_LOADING = 0;
	private static final int MSG_SHOW_LIST = 1;
	private static final int MSG_SHOW_NO_ITEMS = 2;
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch (msg.what) {
			case MSG_SHOW_LOADING:
				setMode(MODE_LOADING);
				break;
			case MSG_SHOW_LIST:
				setMode(MODE_SHOW_LIST);
				backupListView.setAdapter(apksListAdapter);
				break;
			case MSG_SHOW_NO_ITEMS:
				setMode(MODE_SHOW_NO_ITEM);
				break;

			default:
				break;
			}
			super.handleMessage(msg);
		}
	};

}
